<!--
/**
 * author: vformAdmin
 * email: vdpadmin@163.com
 * website: https://www.vform666.com
 * date: 2021.08.18
 * remark: 如果要分发VForm源码，需在本文件顶部保留此文件头信息！！
 */
-->

<template>
  <container-wrapper :designer="designer" :widget="widget" :parent-widget="parentWidget" :parent-list="parentList"
                     :index-of-parent-list="indexOfParentList">
    <div :key="widget.id" class="layout-container" @click.stop="selectWidget(widget)"
         :class="[selected ? 'selected' : '', customClass]">
      <el-tabs v-model="activeTabName" class="tab-container" :type="widget.displayType" @tab-click="onTabClick"
               :tab-position="widget.options.tabPosition" v-if="widget.type === 'tab'">
        <el-tab-pane v-for="(tab, index) in widget.tabs" :key="index" :label="tab.options.label" :name="tab.options.name"
                    @click.stop="selectWidget(widget)" class="vform-desinger-tab-pane">
          <draggable :list="tab.widgetList" item-key="id" 
                    :group="{name: 'dragGroup', pull: (isInLayoutSync && isSyncFromLeft) ? 'clone' : true, put: !isSyncFromLeft}"
                    :clone="(isInLayoutSync && isSyncFromLeft) ? handleClone : undefined"
                    handle=".drag-handler" 
                    tag="transition-group" 
                    :component-data="{name: 'fade'}"
                    ghost-class="ghost"
                    :animation="200"
                    @add="(evt) => onContainerDragAdd(evt, tab.widgetList)"
                    @update="onContainerDragUpdate" 
                    :move="checkContainerMove">
            <template #item="{ element: subWidget, index: swIdx }">
              <div class="form-widget-list">
                <template v-if="'container' === subWidget.category">
                  <component :is="subWidget.type + '-widget'" :widget="subWidget" :designer="designer" :key="subWidget.id" :parent-list="tab.widgetList"
                                :index-of-parent-list="swIdx" :parent-widget="parentWidget"></component>
                </template>
                <template v-else>
                  <component :is="subWidget.type + '-widget'" :field="subWidget" :designer="designer" :key="subWidget.id" :parent-list="tab.widgetList"
                                :index-of-parent-list="swIdx" :parent-widget="parentWidget" :design-state="true"></component>
                </template>
              </div>
            </template>
          </draggable>
        </el-tab-pane>

        <template #addIcon>
          <VfIcon name="iv-icon-plus" @click.stop="addTabPane" title="添加pane" class="add-tab-button"/>
        </template>
      </el-tabs>
    </div>

  </container-wrapper>
</template>

<script>
  import i18n from "@/utils/i18n"
  import containerMixin from "@/components/form-designer/form-widget/container-widget/containerMixin"
  import ContainerWrapper from "@/components/form-designer/form-widget/container-widget/container-wrapper"
  import FieldComponents from '@/components/form-designer/form-widget/field-widget/index'
  import refMixinDesign from "@/components/form-designer/refMixinDesign"

  export default {
    name: "tab-widget",
    componentName: 'ContainerWidget',
    mixins: [i18n, containerMixin, refMixinDesign],
    inject: ['refList'],
    components: {
      ContainerWrapper,
      ...FieldComponents,
    },
    props: {
      widget: Object,
      parentWidget: Object,
      parentList: Array,
      indexOfParentList: Number,
      designer: Object,
    },
    data() {
      return {
        activeTabName: 'tab1',
        //
      }
    },
    computed: {
      selected() {
        return this.widget.id === this.designer.selectedId
      },

      customClass() {
        return this.widget.options.customClass || ''
      },
      
      // 判断是否在同步布局组件内
      isInLayoutSync() {
        let parent = this.parentWidget;
        let depth = 0;
        while (parent && depth < 10) {
          if (parent.type === 'layout-sync') {
            return true;
          }
          parent = parent.parentWidget;
          depth++;
        }
        return false;
      },
    // 判断元素是否来自同步布局的左侧
    isSyncFromLeft() {
      if (this.widget && this.widget.hasOwnProperty('_layoutPosition')) {
        const isFromLeft = this.widget._layoutPosition === 'left';
        return isFromLeft;
      }
      return false;
    }
    },
    watch: {
      //
    },
    created() {
      this.initRefList()
    },
    mounted() {
      //
      this.initActiveTab()
    },
    methods: {
      onTabClick(evt) {
        // let paneName = evt.paneName
        // this.widget.tabs.forEach((tp) => {
        //   tp.options.active = tp.options.name === paneName;
        // })
      },
      initActiveTab() {
        if ((this.widget.type === 'tab') && (this.widget.tabs.length > 0)) {
          let activePanes = this.widget.tabs.filter((tp) => {
            return tp.options.active === true
          })
          if (activePanes.length > 0) {
            this.activeTabName = activePanes[0].options.name
          } else {
            this.activeTabName = this.widget.tabs[0].options.name
          }
        }
      },

      checkWidgetListForLeftElement(widgetList) {
        if (!widgetList || !Array.isArray(widgetList)) {
          return false;
        }
        
        for (let widget of widgetList) {
          if (this.isElementFromLeftList(widget)) {
            return true;
          }
        }
        return false;
      },

      isElementFromLeftList(element) {
        if (element && element.hasOwnProperty('_isFromLeft') && element._isFromLeft === true) {
          return true;
        }
        
        if (element && element.category === 'container') {
          // 特别处理 grid 容器
          if (element.type === 'grid' && element.cols && Array.isArray(element.cols)) {
            for (let col of element.cols) {
              if (col.widgetList && Array.isArray(col.widgetList)) {
                if (this.checkWidgetListForLeftElement(col.widgetList)) {
                  return true;
                }
              }
            }
          }
          
          // 特别处理 tab 容器
          if (element.type === 'tab' && element.tabs && Array.isArray(element.tabs)) {
            for (let tab of element.tabs) {
              if (tab.widgetList && Array.isArray(tab.widgetList)) {
                if (this.checkWidgetListForLeftElement(tab.widgetList)) {
                  return true;
                }
              }
            }
          }
          
          // 处理其他容器的 widgetList
          if (element.widgetList && Array.isArray(element.widgetList) && 
              element.type !== 'grid' && element.type !== 'tab') {
            return this.checkWidgetListForLeftElement(element.widgetList);
          }
          
          // 处理自定义容器组件，如左右布局等
          if (element.leftLists && Array.isArray(element.leftLists)) {
            if (this.checkWidgetListForLeftElement(element.leftLists)) {
              return true;
            }
          }
          
          if (element.rightLists && Array.isArray(element.rightLists)) {
            if (this.checkWidgetListForLeftElement(element.rightLists)) {
              return true;
            }
          }
          
          return false;
        }
        
        return false;
      },

      // 重构深度克隆函数，确保所有嵌套元素都被正确克隆并分配唯一ID
      deepCloneComponent(original) {
        if (!original) return original;
        // 深度克隆组件
        const cloned = JSON.parse(JSON.stringify(original));

        // 生成新的唯一ID
        const generateNewId = () => {
          return 'widget' + Math.random().toString(36).substring(2, 10) + Date.now().toString(36);
        };

        // 递归处理所有嵌套组件的ID
        const processWidgetIds = (widget) => {
          if (!widget) return;

          // 为当前组件生成新ID
          widget.id = generateNewId();
          
          if (widget.guid) {
            widget.guid = generateNewId().toUpperCase();
          }
          // 递归处理容器组件的子组件
          if (widget.category === 'container') {
            // 处理 grid 容器
            if (widget.type === 'grid' && widget.cols && Array.isArray(widget.cols)) {
              widget.cols.forEach((col) => {
                if (col) {
                  col.id = generateNewId();
                  
                  if (col.guid) {
                    col.guid = generateNewId().toUpperCase();
                  }
                  
                  // 递归处理 grid-col 内部的 widgetList
                  if (col.widgetList && Array.isArray(col.widgetList)) {
                    col.widgetList.forEach(processWidgetIds);
                  }
                }
              });
            }

            // 处理 tab 容器
            if (widget.type === 'tab' && widget.tabs && Array.isArray(widget.tabs)) {
              widget.tabs.forEach((tab) => {
                if (tab) {
                  tab.id = generateNewId();
                  
                  if (tab.guid) {
                    tab.guid = generateNewId().toUpperCase();
                  }
                  
                  // 递归处理 tab 内部的 widgetList
                  if (tab.widgetList && Array.isArray(tab.widgetList)) {
                    tab.widgetList.forEach(processWidgetIds);
                  }
                }
              });
            }

            // 特别处理 grid-col 容器
            if (widget.type === 'grid-col' && widget.widgetList && Array.isArray(widget.widgetList)) {
              widget.widgetList.forEach(processWidgetIds);
            }

            // 处理其他容器的 widgetList
            if (widget.widgetList && Array.isArray(widget.widgetList) && 
                widget.type !== 'grid' && widget.type !== 'tab' && widget.type !== 'grid-col') {
              widget.widgetList.forEach(processWidgetIds);
            }

            // 处理自定义容器组件，如左右布局等
            if (widget.leftLists && Array.isArray(widget.leftLists)) {
              widget.leftLists.forEach(processWidgetIds);
            }
            
            if (widget.rightLists && Array.isArray(widget.rightLists)) {
              widget.rightLists.forEach(processWidgetIds);
            }
          }
        };

        // 处理克隆后的组件及其所有嵌套组件的ID
        processWidgetIds(cloned);
        return cloned;
      },

      handleClone(original) {
        // 检查是否在同步布局内，如果不在，则不进行克隆
        if (!this.isInLayoutSync) {
          // 不在同步布局中时，返回原对象（移动而不是复制）
          return original;
        }
        
        // 使用组件自身的深度克隆方法
        return this.deepCloneComponent(original);
      },
      onContainerDragAdd(evt, widgetList) {
        const { newIndex } = evt;
        if ((newIndex === undefined) || (newIndex === null)) {
          return;
        }

        // 检查是否在同步布局中
        const isInSyncLayout = this.isInLayoutSync;
        const newWidget = widgetList[newIndex];
        if (!!newWidget) {
          let clonedWidget = null;
          
          // 只有在同步布局中才进行克隆操作
          if (isInSyncLayout) {
            // 检查是否是从左侧列表拖拽过来的
            if (this.isElementFromLeftList && this.isElementFromLeftList(newWidget)) {
              // 使用同步布局自己的深度克隆方法
              clonedWidget = this.deepCloneComponent(newWidget);
            } else if (newWidget.category === 'container') {
              if (this.designer) {
                clonedWidget = this.designer.copyNewContainerWidget(newWidget);
              }
            } else if (newWidget.category === 'field') {
              if (this.designer) {
                clonedWidget = this.designer.copyNewFieldWidget(newWidget);
              }
            }
            
            // 如果成功克隆，则替换原组件
            if (clonedWidget) {
              widgetList.splice(newIndex, 1, clonedWidget);
              this.designer.setSelected(clonedWidget);
            } else {
              this.designer.setSelected(newWidget);
            }
          } else {
            // 非同步布局中直接使用原组件
            this.designer.setSelected(newWidget);
          }
          
          this.designer.emitHistoryChange();
        }
      },

      onContainerDragUpdate() {
        this.designer.emitHistoryChange();
      },

      checkContainerMove(evt) {
        return this.designer.checkWidgetMove(evt);
      },
    }
  }
</script>

<style lang="scss" scoped>
  .tab-container {
    //padding: 5px;
    margin: 2px;

    .form-widget-list {
      min-height: 28px;
    }
    :deep(.el-tabs) {
      box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
    }
    :deep(.el-tabs__header) {
      margin-bottom: 0;
    }
    :deep(.el-tabs__nav-scroll) {
      padding: 0 5px;
    }
    :deep(.el-tabs__content) {
      min-height: 30px;
      padding: 15px
    }
  }

  .tab-container.selected {
    outline: 2px solid $--color-primary !important;
  }
.vform-desinger-tab-pane {
  min-height: 60px;
}
</style>
